package com.babarus.netmonitor;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.app.IntentService;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

public class ConnectionService extends IntentService{
	  
	private static final String TAG = null;
	private int result = Activity.RESULT_CANCELED;	
	
	 public ConnectionService() {
		 super("ConnectionService");
	 }

	
	  // Will be called asynchronously be Android
	  protected void onHandleIntent(Intent intent) {
		  result = Activity.RESULT_OK;

 	      Bundle extras = intent.getExtras();
		  if (extras != null) {
		      Messenger messenger = (Messenger) extras.get("MESSENGER");
	      	  String deviceAddress = (String) extras.get("deviceAddress");
	      	  
		      Message msg = Message.obtain();
		      msg.arg1 = result;
		      Bundle bundleData = new Bundle();

		      String serverResponce = getUrlContent(deviceAddress);
	      
		      bundleData.putString("requestContent", serverResponce );
		      
		      msg.setData(bundleData);
		      
		      try {
		        messenger.send(msg);
		      } catch (android.os.RemoteException e1) {
		        Log.w(getClass().getName(), "Exception sending message", e1);
		      }
	      
	
		  }
	    
	    
	  }
	  
	  
	  
	  public String getUrlContent(String deviceAddress){	   		
	    	String xmlContent = "";
	    	URL deviceUrl;
			try {
				deviceUrl = new URL(deviceAddress);
		    	BufferedReader in = new BufferedReader(new InputStreamReader(deviceUrl.openStream()));
		
		    	String inputLine;
		
		    	while ((inputLine = in.readLine()) != null){
		    	    xmlContent = xmlContent+inputLine;
		    	}
		    	in.close();
		    	
			} catch (MalformedURLException e) {
				//e.printStackTrace();
				return getApplicationContext().getResources().getString(R.string.error_no_response);
			} catch (IOException e) {
				//e.printStackTrace();
				return getApplicationContext().getResources().getString(R.string.error_no_response);
			}

	   	 	//System.out.println(xmlContent);
	    	//this.parseXML();
	    	
	    	return xmlContent;
	    }	  

}
